﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;

namespace MichMan.Utilities.Requests
{
    public class CachedValue<T>
    {
        public CachedValue(ICache cache, string key)
        {
            _cache = (cache == null) ? new NoCache() : cache;
            DefaultValue = () => default(T);
            _key = key;
        }

        public TimeSpan? Lifetime { get; set; }

        private Func<T> _defaultValue;
        public Func<T> DefaultValue
        {
            get { return _defaultValue; }
            set
            {
                if (value == null)
                {
                    _defaultValue = () => default(T);
                }
                _defaultValue = value;
            }
        }

        private ICache _cache = null;
        private string _key = null;

        public T Value
        {
            set
            {
                if (_key == null)
                {
                    return;
                }

                _cache.Insert(_key, value, Lifetime);
            }

            get
            {
                if (_key == null)
                {
                    return DefaultValue();
                }

                if (_cache.Get(_key) == null)
                {
                    T _value = DefaultValue();
                    if (_value != null)
                    {
                        _cache.Insert(_key, _value, Lifetime);
                    }
                }
                else
                {
                    return _cache.Get<T>(_key);
                }

                return DefaultValue();
            }
        }
    }
}
